package com.umbrella.security;

import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import com.alibaba.fastjson.JSON;

public class AES {

    final static String transformation = "AES/ECB/PKCS5Padding";
    final static String _CHARSET = "UTF-8";   

    public static String encrypt(String data, String key) throws Exception {

        SecretKeySpec skey = new SecretKeySpec(key.getBytes(_CHARSET), "AES");
        Cipher cipher = Cipher.getInstance(transformation);
        cipher.init(Cipher.ENCRYPT_MODE, skey);
        byte[] result = cipher.doFinal(data.getBytes(_CHARSET));

        return Base64.getEncoder().encodeToString(result);
    }

    public static String decrypt(String data, String key) throws Exception{

        SecretKeySpec skey = new SecretKeySpec(key.getBytes(_CHARSET), "AES");
        Cipher cipher = Cipher.getInstance(transformation);
        cipher.init(Cipher.DECRYPT_MODE, skey);
        byte[] decryptBytes = cipher.doFinal(Base64.getDecoder().decode(data));

        return new String(decryptBytes, _CHARSET);
    }
    
    public static <T> T decrypt(String data, String key, Class<T> clazz) throws Exception{

        SecretKeySpec skey = new SecretKeySpec(key.getBytes(_CHARSET), "AES");
        Cipher cipher = Cipher.getInstance(transformation);
        cipher.init(Cipher.DECRYPT_MODE, skey);
        byte[] decryptBytes = cipher.doFinal(Base64.getDecoder().decode(data));

        String result = new String(decryptBytes, _CHARSET);
        return JSON.parseObject(result, clazz);
    }
}
